var fs = require('fs');
var request = require('request');
var htmlUtil = require('../util/html.js');

function downloadImgFromNasa(file) {
    request('http://apod.nasa.gov/apod/astropix.html', function(error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(htmlUtil.getOneImage(body, 'center'));
            request('http://apod.nasa.gov/' + htmlUtil.getOneImage(body, 'center')).pipe(fs.createWriteStream(file))
        }
    })
};

function downloadImgFromCurator(file) {
    request('http://curator.im/girl_of_the_day', function(error, response, body) {
        if (!error && response.statusCode == 200) {
            var imgurl = htmlUtil.getOneImage(body, 'body');
            console.log(imgurl);
            request(imgurl).pipe(fs.createWriteStream(file));
        }
    })
};

exports.downloadImg = function(file) {
    if (file == 'public/images/nasa.jpg') {
        downloadImgFromNasa(file);
    } else if (file == 'public/images/curator.jpg') {
        downloadImgFromCurator(file);
    }
}